package com.sifeng.test;

import com.sifeng.enums.FileTypeEnum;
import com.sifeng.utils.MyUtils;
import org.apache.commons.io.FileUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by yang_gsh on 2018/10/7.
 * 将文件按日期进行分类，导入到文件日期分类的文件夹中
 */
public class DocumentsAreClassifiedByDate {
	//获取文件创建日期
	private static Date getCreateTime(String fullFileName){
		Path path= Paths.get(fullFileName);
		BasicFileAttributeView basicview= Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS );
		BasicFileAttributes attr;
		try {
			attr = basicview.readAttributes();
			//Date createDate = new Date(attr.creationTime().toMillis());
			Date createDate = new Date(attr.lastModifiedTime().toMillis());
			return createDate;
		} catch (Exception e) {
			e.printStackTrace();
		}
		Calendar cal = Calendar.getInstance();
		cal.set(1970, 0, 1, 0, 0, 0);
		return cal.getTime();
	}

	public static void executeMoveFile(String dirPath) {
		List<String> fileList = MyUtils.readDirectory(dirPath, FileTypeEnum.FILE);
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMM");

		for (String s : fileList) {
			String filePath = dirPath + "\\" + s;
			Date createTime = getCreateTime(filePath);
			String createTime_tmp = simpleDateFormat.format(createTime);
			if (createTime_tmp == "197001") {
				continue;
			} else {
				//System.out.println(createTime_tmp);
				try {
					FileUtils.moveFileToDirectory(new File(filePath), new File(dirPath + "\\" + createTime_tmp),true);
				} catch (IOException e) {
					e.printStackTrace();
					continue;
				}
			}
		}
	}

	public static void main(String[] args) {
		executeMoveFile("K:\\沫沫");
	}
}